package com.koron.css2.clientCenter.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.mapper.BusinessAreaMapper;
import com.koron.css2.clientCenter.bean.*;
import com.koron.css2.clientCenter.mapper.AccountInfoMapper;
import com.koron.css2.clientCenter.mapper.CtmInfoMapper;
import com.koron.css2.clientCenter.mapper.UserInfoMapper;
import com.koron.css2.meterService.dto.MsInfoDto;
import com.koron.css2.meterService.mapper.MsInfoMapper;
import com.koron.css2.serviceManage.bean.*;
import com.koron.css2.serviceManage.mapper.PubAdminAreaMapper;
import com.koron.css2.serviceManage.mapper.UserDiscountMapper;
import com.koron.css2.serviceManage.mapper.UserMixtureMapper;
import com.koron.css2.serviceManage.queryBean.UserMixtureQueryBean;
import com.koron.css2.serviceManage.vo.UserDiscountVO;
import com.koron.css2.serviceManage.vo.UserMixtureVO;
import com.koron.util.*;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.transaction.annotation.Transactional;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 开户修改接口，修改临时客户表、临时账户表、临时用户表
 * 
 * @author 甄玉晴
 *
 */
public class OpenAccUpdate implements ServerInterface {

	@Override
	@ValidationKey(clazz = OpenUserBean.class,method = "update")
	@Transactional(rollbackFor = Exception.class)
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		try {
			UserInfoMapper userMapper = factory.getMapper(UserInfoMapper.class);
			OpenUserBean bean = JsonUtils.objectToPojo(req.getData(), OpenUserBean.class);
			// 获取临时用户信息
			UserBean openUserInfo = userMapper.getUserInfoById(bean.getUserOpenInfo().getUserInfoTempId(), UserBean.USERTEMP);

			MsInfoMapper meterMapper = factory.getMapper(MsInfoMapper.class);
			bean.getUserInfo().setMeterType("1");

			//修改时更换了水表编号
			if (!openUserInfo.getMeterNo().equals(bean.getUserInfo().getMeterNo())){
				if("1".equals(bean.getUserInfo().getMeterType())) {
					String meterNo = meterMapper.getMeterSatus(bean.getUserInfo().getMeterNo());
					if(meterNo==null || !"1".equals(meterNo)){
						return MessageBean.create(Constant.ILLEGAL_PARAMETER, "该水表不是在库表，不能开户", void.class);
					}
				}
				//将原先水表释放为在库，新水表改为在用
				meterMapper.updateMsInfoStatus(openUserInfo.getMeterNo(),1);
				meterMapper.updateMsInfoStatus(bean.getUserInfo().getMeterNo(),2);
			}

			// 校验,待确定
			// TODO Auto-generated method stub
			//获取开户信息
			UserOpenBean openUser=bean.getUserOpenInfo();
			// 获取客户信息,如果标志为可修改则进行更新
			CtmInfoBean ctmInfo = bean.getCtmInfo();
			
			PubAdminAreaMapper pmapper = factory.getMapper(PubAdminAreaMapper.class,"_default");
			String clientAddr=pmapper.selectFullNameById(ctmInfo.getClientAddr());
			if(StringUtils.isEmpty(clientAddr)) {
				ctmInfo.setClientAddr(null);
			}

			ctmInfo.setCtmAddr(Tools.StringValueOf(clientAddr,ctmInfo.getClientAddrDetail()));
			OpenUserAdd openCheck = new OpenUserAdd();
			if("1".equals(ctmInfo.getCertType())) {
				if(!openCheck.checkIdentityCode(ctmInfo.getCertNo())) {
					return MessageBean.create(Constant.ILLEGAL_PARAMETER, "无效的身份证号码", void.class);
				};
			}
			ctmInfo.setId(openUser.getUserCtmTempId());
			ctmInfo.setUpdateInfo(userInfo);
			CtmInfoMapper ctmMapper = factory.getMapper(CtmInfoMapper.class);
			
			
			ctmMapper.ctmInfoUpdateForTransfer(ctmInfo, CtmInfoBean.CTMTEMP);
			
			// 获取账户信息,如果标志为可修改则进行更新
			AccountInfoBean accountInfo = bean.getAccountInfo();
			// 获取账户信息
			if(StringUtils.isEmpty(accountInfo.getAccountNo())) {
				accountInfo.setAccountNo(Tools.getBillNo(factory, "USER_ACCOUNT", userInfo.getCurWaterCode()));
			}
			accountInfo.setId(openUser.getUserAccountTempId());
			accountInfo.setUpdateInfo(userInfo);
			AccountInfoMapper accountMapper = factory.getMapper(AccountInfoMapper.class);
			accountMapper.accountInfoUpdateForTransfer(accountInfo, AccountInfoBean.ACCOUNTTEMP);

			UserBean user = bean.getUserInfo();
			//获取配置参数，是否取营业区域默认册本号-开始
			BusinessAreaMapper businessAreaMapper = factory.getMapper(BusinessAreaMapper.class);
			String dbEnv = DBSourceUtils.getDbEnv(userInfo.getCurWaterCode());
			String on_off = Tools.getConfigValue(dbEnv, "DEFAULT_BOOK_NO_ON_OFF");
			if("1".equals(on_off)) {
				BusinessAreaBean business = businessAreaMapper.findBusinessAreaInfoById(user.getBusinessArea());
				user.setBookNo(business.getBookNo());
			}
			//-结束
			String clientContractAddr = pmapper.selectFullNameById(user.getClientContractAddr());
			if(StringUtils.isEmpty(clientContractAddr)) {
				user.setClientContractAddr(null);
			}
			user.setSetupMeterAddr(Tools.StringValueOf(clientContractAddr,user.getClientContractAddrDetail()));

			//装表地址默认设置为结构化地址拼接
			//user.setSetupMeterAddr(user.getClientContractAddr()+"->"+user.getClientContractAddrDetail());
			user.setId(openUser.getUserInfoTempId());
			user.setCtmNo(ctmInfo.getCtmNo());
			user.setAccountNo(accountInfo.getAccountNo());
			user.setUpdateInfo(userInfo);
			OpenUserAdd.ctmInfoToUserInfo(ctmInfo,user);
			userMapper.userInfoUpdate(user,UserBean.USERTEMP); 
			
			//修改混合用水
			if(bean.getUserMixtureData() != null) {
				UserMixtureMapper userMixtureMapper = factory.getMapper(UserMixtureMapper.class);
				UserMixtureVO vo = bean.getUserMixtureData();

				UserMixtureQueryBean queryBean = new UserMixtureQueryBean();
				queryBean.setId(openUser.getId());
				queryBean.setUserNo(user.getUserNo());
				List<UserMixtureBean> exits = userMixtureMapper.listTemp(queryBean);
				List<UserMixtureBean> mixtureBeans = new ArrayList<UserMixtureBean>();
				mixtureBeans.addAll(exits);
				for(UserMixtureBean userMixtureBean:vo.getList()) {			//判断该记录是否已存在,存在则更新，不存在则添加
						int isExits = 0;
						for(UserMixtureBean exit: exits) {
							if(userMixtureBean.getUserNo().equals(exit.getUserNo()) && 
									userMixtureBean.getUseWaterType().equals(exit.getUseWaterType())  && 
										userMixtureBean.getCostNo().equals(exit.getCostNo())) {
								isExits =1;
								userMixtureBean.setUpdateInfo(userInfo);
								userMixtureMapper.updateTemp(userMixtureBean);
								mixtureBeans.remove(exit);
							}
						}
						if(isExits == 0) {
							userMixtureBean.setCreateInfo(userInfo);
							userMixtureBean.setTenantId(openUser.getId());
							userMixtureMapper.insertTemp(userMixtureBean);
						}
						
				}
				
				for(UserMixtureBean mixtureBean :mixtureBeans) {
					userMixtureMapper.deleteTemp(mixtureBean);
				}
				
			}
			
			//修改费用折扣
			if(bean.getDiscountData() != null) {
				UserDiscountMapper userDiscountMapper = factory.getMapper(UserDiscountMapper.class);
				UserDiscountVO vo = bean.getDiscountData();
			//	userDiscountMapper.deleteTemp(openUser.getId());
				UserMixtureQueryBean queryBean = new UserMixtureQueryBean();
				queryBean.setId(openUser.getId());
				queryBean.setUserNo(user.getUserNo());
				List<UserDiscountBean> exits = userDiscountMapper.listTemp(queryBean);
				List<UserDiscountBean> discountBeans = new ArrayList<UserDiscountBean>();
				discountBeans.addAll(exits);
				for(UserDiscountBean userDiscountBean:vo.getList()) {	
					int isExits = 0;
					for(UserDiscountBean exit: exits) {
						if(userDiscountBean.getUserNo().equals(exit.getUserNo()) && userDiscountBean.getCostId().equals(exit.getCostId())) {
							isExits =1;
							userDiscountBean.setUpdateInfo(userInfo);
							userDiscountMapper.updateTemp(userDiscountBean);
							discountBeans.remove(exit);
						}
					}
					if(isExits == 0) {
						userDiscountBean.setCreateInfo(userInfo);
						userDiscountBean.setTenantId(openUser.getId());
						userDiscountMapper.insertTemp(userDiscountBean);
					}
				}
				
				for(UserDiscountBean discountBean :discountBeans) {
					userDiscountMapper.deleteTemp(discountBean);
				}
			}
			//返回水表IMST
			MsInfoMapper msmapper = factory.getMapper(MsInfoMapper.class);
			MsInfoDto meter = msmapper.getMsInfoByNo(user.getMeterNo());
			//返回详情列表行数据
			Map<String, String> map = new HashMap<String, String>();
			map.put("id", openUser.getId());
			map.put("ctmNo", ctmInfo.getCtmNo());
			map.put("accountNo", user.getAccountNo());
			map.put("userNo", user.getUserNo());
			map.put("ctmName", ctmInfo.getCtmName());
			map.put("bookNo", user.getBookNo());
			map.put("businessAreaName", user.getBusinessAreaName());
			map.put("setupMeterAddr", user.getSetupMeterAddr());
			map.put("setupMeterDate", user.getSetupMeterDate());
			map.put("useWaterTypeName",user.getUseWaterTypeName());
			map.put("imei",meter.getImei());
			map.put("imsi",meter.getImsi());
			@SuppressWarnings("rawtypes")
			MessageBean<Map> msg = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "保存成功", Map.class);
			msg.setData(map);
			return msg;
		} catch (Exception e) {
			logger.error("开户修改失败", e);
			return MessageBean.create(Constant.MESSAGE_INT_FAIL, "开户修改失败", void.class);
		}
	}

}
